<template>
  <div>
    <div class="title flex mgt">
      <div class="flex1">工作经历</div>
      <img src="../../assets/home/add.png" alt="" class="add" @click="addExperience">
    </div>
    <div v-for="(item, index) in work_experience" :key="index">
      <!-- 编辑或新增状态显示表单 -->
      <div v-if="isEditing(index)" class="flex mainlist-hovers">
        <el-form :model="item" :rules="rules" :ref="(el) => { if (el) formRefs[index] = el }" label-width="100px"
          label-position="top">
          <div class="demo-ruleForm flex-between flex-wrap">
            <el-form-item label="公司名称" prop="company">
              <el-input v-model="item.company"></el-input>
            </el-form-item>
            <el-form-item label="职位名称" prop="post">
              <el-input v-model="item.post"></el-input>
            </el-form-item>
            <el-form-item label="在职时间" prop="range">
              <el-date-picker v-model="item.range" type="daterange" start-placeholder="开始时间" end-placeholder="结束时间"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
            </el-form-item>
          </div>
          <el-form-item label="工作描述" prop="desc">
            <el-input type="textarea" v-model="item.desc"></el-input>
          </el-form-item>
          <el-form-item class="flex">
            <div class="flex1"></div>
            <el-button @click="cancelEdit(index)">取消</el-button>
            <el-button type="primary" @click="save(index)">保存</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 非编辑状态显示内容 -->
      <div v-else class="main-jinglist mainlist-hover" @mouseenter="showTooltip(index)" @mouseleave="hideTooltip">
        <div class="flex">
          <div class="flex1">{{ item.company }}</div>
          <div class="time">{{ item.range[0] || '-'}} - {{ item.range[1] || '-' }}</div>
          <div class="flex bianji" v-show="isTooltipVisible && tooltipIndex === index">
            <div class="flex" @click="startEdit(index)">
              <img src="../../assets/home/bianji.png" alt="" class="del">
              编辑
            </div>
            <div class="flex delnum" @click="remove(index)">
              <img src="../../assets/home/del.png" alt="" class="del">
              删除
            </div>
          </div>
        </div>
        <div class="yuan">{{ item.post }}</div>
        <div class="left-miaoshu">
          <div>工作描述:</div>
          <p>{{ item.desc }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, toRefs } from 'vue';

const formRefs = ref([]);
const props = defineProps({
  work_experience: {
    type: Array,
    default: () => []
  }
});

const emit = defineEmits(['save', 'remove']);

const editingIndex = ref(-1); // -1 表示没有正在编辑的项
const isTooltipVisible = ref(false);
const tooltipIndex = ref(-1);
// 表单校验规则
const rules = {
  company: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
  post: [{ required: true, message: '请选择职位名称', trigger: 'change' }],
  range: [{ required: true, validator: validateRange, trigger: 'change' }],
  desc: [{ required: true, message: '请输入专业描述', trigger: 'blur' }]
};
// 使用计算属性来管理内部数据
const { work_experience } = toRefs(props);
// 判断是否正在编辑某一项
const isEditing = (index) => {
  return editingIndex.value === index;
};

// 开始编辑
const startEdit = (index) => {
  editingIndex.value = index;
};

// 新增工作经历
const addExperience = () => {
  const newExperience = {
    company: '',
    post: '',
    range: [null, null],
    desc: ''
  };
  work_experience.value.unshift(newExperience);
  editingIndex.value = 0;
};

// 取消编辑
const cancelEdit = (index) => {
  if (editingIndex.value === 0 && !work_experience.value[0]?.company) {
    work_experience.value.splice(0, 1);
  }
  editingIndex.value = -1;
  // 恢复到 props 的原始数据
  const formRef = formRefs.value[index];
  formRef.resetFields()
};

// 保存
const save = async (index) => {
  const formRef = formRefs.value[index];
  if (formRef) {
    await formRef.validate();
    emit('save', {
      type: 'work_experience',
      data: work_experience.value
    });
    editingIndex.value = -1;
    // 保存成功后更新父组件数据
  }
};

// 校验函数
function validateRange(rule, value, callback) {
  if (!value || !value.length || value.some(v => !v)) {
    return callback(new Error('请选择开始时间和结束时间'));
  }

  const [startDate, endDate] = value;

  if (new Date(startDate).getTime() > new Date(endDate).getTime()) {
    return callback(new Error('结束时间不能早于开始时间'));
  }

  callback();
}

const remove = (index) => {
  work_experience.value.splice(index, 1);
  emit('save', {
    type: 'work_experience',
    data: work_experience.value
  });
};

const showTooltip = (index) => {
  isTooltipVisible.value = true;
  tooltipIndex.value = index;
};

const hideTooltip = () => {
  isTooltipVisible.value = false;
  tooltipIndex.value = -1;
};

const formatDate = (date) => {
  return date ? new Date(date).toLocaleDateString() : '';
};

</script>
<style scoped>
@import url("./cmmon.scss");
</style>
